

# 登录接口 https://www.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fwww.gushiwen.cn%2fuser%2fcollect.aspx

# 参数如下：
# __VIEWSTATE: dXlHxPftyk4OmBqEjkCmwg5ZERR99WHKhqZsdBIAVkRdIvIJudn+h/imCKvD7gyw9r3wbgpYlMmodCPKZ41j6E+MfTSeo2NY6Fs3n4tSX8tDCCafv4uM+LCIo+o9KzvukoVFOajsbsCRK0H/XzIJGkHQeZ0=
# __VIEWSTATEGENERATOR: C93BE1AE
# from: http://www.gushiwen.cn/user/collect.aspx
# email: 123123123@qq.com
# pwd: 123123123
# code: hw27
# denglu: 登录

# 从登录入参中，看到可变参数有： __VIEWSTATE   __VIEWSTATEGENERATOR   code
#  __VIEWSTATE   __VIEWSTATEGENERATOR 数据获取一般在网页源码中
# code 验证码


import requests

# 登录页面url
url = 'https://www.gushiwen.cn/user/login.aspx?from=http://www.gushiwen.cn/user/collect.aspx'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
}

response = requests.get(url=url, headers=headers)
content = response.text
# print(content) # 获取网页源码

# 解析网页源码 使用BeautifulSoup
from bs4 import BeautifulSoup
soup = BeautifulSoup(content, 'lxml')

# 获取 id:__VIEWSTATE 标签value 值
viewstate = soup.select('#__VIEWSTATE')[0].attrs.get('value')
print(viewstate)
# 获取 id:__VIEWSTATEGENERATOR 标签value 值
viewstategenerator = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')
print(viewstategenerator)

# 获取验证码 code 图片
code_src = soup.select('#imgCode')[0].attrs.get('src')
code_url = 'https://www.gushiwen.cn' + code_src
print(code_url)

# 将验证码下载下来--有坑！！！原因：验证码和登录应属于同一个请求；
# import urllib.request
# urllib.request.urlretrieve(url=code_url, filename='code.jpg')

session = requests.session()
response_code = session.get(code_url)
# 这里返回的是一个二进制文件
content_code = response_code.content
# 将二进制文件写入本地
with open('code.jpg', 'wb') as fp:
    fp.write(content_code)
print('验证码下载完成。。。')
code_val = input('输入验证码：')

# 登录接口 - post
login_url = 'https://www.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fwww.gushiwen.cn%2fuser%2fcollect.aspx'
login_data = {
    '__VIEWSTATE': viewstate,
    '__VIEWSTATEGENERATOR': viewstategenerator,
    'from': 'http://www.gushiwen.cn/user/collect.aspx',
    'email': '3502384335@qq.com',
    'pwd': '123456',
    'code': code_val,
    'denglu': '登录'
}

login_response = session.post(url=login_url, data=login_data, headers=headers)
login_content = login_response.text
with open('gushiwenwang.html', 'w', encoding='utf-8') as fp:
    fp.write(login_content)
print('登录成功...')
# 打开 看 gushiwenwang.html 是否登录成功看到，我的；

# 难点
# 1.隐藏域 (指：__VIEWSTATE 和 __VIEWSTATEGENERATOR input type='hidden')
# 2.验证码



